package com.abel.repository.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.abel.datamodel.type.Applicants;
import com.abel.datamodel.type.MilitaryServices;
import com.abel.domain.MilitaryService;
import com.abel.domain.PersonSearchCriteria;
import com.abel.repository.MilitaryServiceRepository;
import com.abel.repository.exception.NonExistantProfileException;
import com.abel.repository.exception.RepositoryException;
import com.abel.util.UserSessionLocator;

public class MilitaryServiceRepositoryImpl  extends BaseRepositoryImpl implements MilitaryServiceRepository {

	    protected final Log logger = LogFactory.getLog(getClass());

	    /* (non-Javadoc)
		 * @see com.abel.repository.MilitaryServiceRepository#addMilitaryService(com.abel.domain.MilitaryService)
		 */
		@Override
		public int addMilitaryService(MilitaryService mlts) throws RepositoryException 
		{
		    logger.debug("@MilitaryServiceRepositoryimpl : addMilitaryService : entered");
		
		    Transaction tx = null;
			Session session = null;
			MilitaryServices mltss = new MilitaryServices();
			
			try {
				session = this.getSessionFactory().getCurrentSession();
				tx = session.beginTransaction();
				
				//add an mlts record
//				Person person = UserSessionLocator.getUserSession().getPerson();
				mltss.setAplId(mlts.getAplId()); // person.getApplication().getApplicationId());
				mltss.setMltInductionDate(mlts.getMltInductionDate());
				mltss.setMltDischargeDate(mlts.getMltDischargeDate());
		    	mltss.setMltBranch(mlts.getMltBranch());
		    	mltss.setMltRank(mlts.getMltRank());
		    	mltss.setMltDutyDesc(mlts.getMltDutyDesc());
		    	mltss.setMltSplTrainDesc(mlts.getMltSplTrainDesc());
				mltss.setMltCreateDts(new java.sql.Timestamp(System.currentTimeMillis()));

				//saving personal information
				int mltServiceId = Integer.parseInt(((Object)session.save(mltss)).toString());
				tx.commit();
				
				return mltServiceId;
		
		} 
		catch (RuntimeException e) {

			logger.info("@MilitaryServiceRepositoryImpl : addMilitaryService : exception - exception while adding mlts for application id = " + mlts.getAplId());
			e.printStackTrace();
			
			if (tx != null && tx.isActive()) {
			
				try {
				
					tx.rollback();
				
				} 
				catch (HibernateException he) {
					logger.debug("@MilitaryServiceRepositoryImpl : addMilitaryService : exception while rolling back miltary service" + he);
					he.printStackTrace();
				}
			}
			throw new RepositoryException("Exception while adding military service.",e);
		}

	}


		/* (non-Javadoc)
		 * @see com.abel.repository.MilitaryServiceRepository#updateMilitaryService(com.abel.domain.MilitaryService)
		 */
		@Override
		public void updateMilitaryService(MilitaryService mlts) throws RepositoryException {
		    logger.debug("@MilitaryServiceRepositoryimpl : deleteMilitaryService : entered");
			
		    Transaction tx = null;
			Session session = null;
			MilitaryServices mltss = new MilitaryServices();
			
			try {
				session = this.getSessionFactory().getCurrentSession();
				tx = session.beginTransaction();
				
				//update military service record
				mltss.setMltServiceId(mlts.getMltServiceId());
				mltss.setAplId(mlts.getAplId()); 
				mltss.setMltInductionDate(mlts.getMltInductionDate());
				mltss.setMltDischargeDate(mlts.getMltDischargeDate());
		    	mltss.setMltBranch(mlts.getMltBranch());
		    	mltss.setMltRank(mlts.getMltRank());
		    	mltss.setMltDutyDesc(mlts.getMltDutyDesc());
		    	mltss.setMltSplTrainDesc(mlts.getMltSplTrainDesc());

				//getting userId from UserSession
				int userId = UserSessionLocator.getUserSession().getAuthPrincipal().getUserId();
				if (userId <= 0) {
					throw new RepositoryException("Cannot update military service information. UserId in authPrincipal is " + userId);
				}
		
				//updating military service information
				session.update(mltss);
				tx.commit();
				
		} 
		catch (RuntimeException e) {
			
			logger.info("@ : addMilitaryService : exception while adding military service for application id = " + mlts.getAplId());
			e.printStackTrace();
			
			if (tx != null && tx.isActive()) {
			
				try {
						tx.rollback();
					} 
					catch (HibernateException he) {
						logger.debug("@MilitaryServiceRepositoryImpl : updateMilitaryService : exception while rolling back mlts" + he);
						he.printStackTrace();
					}
				}
				throw new RepositoryException("Exception while updating mlts.",e);
			}
		}

//		/* (non-Javadoc)
//		 * @see com.abel.repository.MilitaryServiceRepository#deleteMilitaryService(com.abel.domain.MilitaryService)
//		 */
//		@Override
//		public void deleteMilitaryService(int aplId, int mltServiceId) throws RepositoryException {
//		    logger.debug("@MilitaryServiceRepositoryimpl : deleteMilitaryService : entered");
//			
//		    Transaction tx = null;
//			Session session = null;
//			MilitaryServices mltss = new MilitaryServices();
//			
//			try {
//				session = this.getSessionFactory().getCurrentSession();
//				tx = session.beginTransaction();
//				
//				//delete mlts record
//				mltss.setMltServiceId(mltServiceId);
//				mltss.setAplId(aplId);
//
//				session.delete(mltss);
//				tx.commit();
//				
//		} 
//		catch (RuntimeException e) {
//			//TODO check for duplicate key exception and throw it
//			logger.info("@ : deleteMilitaryService : exception - delete failed for Military_service_id= " + mltServiceId);
//			e.printStackTrace();
//			
//			if (tx != null && tx.isActive()) {
//			
//				try {
//						tx.rollback();
//					} 
//					catch (HibernateException he) {
//						logger.debug("@MilitaryServiceRepositoryImpl : deleteMilitaryService : exception while rolling back mlts" + he);
//						he.printStackTrace();
//					}
//				}
//				throw new RepositoryException("Exception while deleteing mlts.",e);
//			}
//		}
//
//		/* (non-Javadoc)
//		 * @see com.abel.repository.MilitaryServiceRepository#deleteMilitaryService(com.abel.domain.MilitaryService)
//		 */
//		@Override
//		public void deleteMilitaryService(int mltServiceId) throws RepositoryException {
//		    logger.debug("@MilitaryServiceRepositoryimpl : deleteMilitaryService : entered");
//			
//		    Transaction tx = null;
//			Session session = null;
//			MilitaryServices mltss = new MilitaryServices();
//			
//			try {
//				session = this.getSessionFactory().getCurrentSession();
//				tx = session.beginTransaction();
//				
//				//delete mlts record
//				mltss.setMltServiceId(mltServiceId);
//
//				session.delete(mltss);
//				tx.commit();
//				
//		} 
//		catch (RuntimeException e) {
//			//TODO check for duplicate key exception and throw it
//			logger.info("@ : deleteMilitaryService : exception - delete failed for Military_service_id= " + mltServiceId);
//			e.printStackTrace();
//			
//			if (tx != null && tx.isActive()) {
//			
//				try {
//						tx.rollback();
//					} 
//					catch (HibernateException he) {
//						logger.debug("@MilitaryServiceRepositoryImpl : deleteMilitaryService : exception while rolling back mlts" + he);
//						he.printStackTrace();
//					}
//				}
//				throw new RepositoryException("Exception while deleteing mlts.",e);
//			}
//		}

		/* (non-Javadoc)
		 * @see com.abel.repository.MilitaryServiceRepository#deleteMilitaryService(com.abel.domain.MilitaryService)
		 */
		@Override
		public void deleteMilitaryService(MilitaryService mlts) throws RepositoryException {
		    logger.debug("@MilitaryServiceRepositoryimpl : deleteMilitaryService : entered");
			
		    Transaction tx = null;
			Session session = null;
			MilitaryServices mltss = new MilitaryServices();
			
			try {
				session = this.getSessionFactory().getCurrentSession();
				tx = session.beginTransaction();
				
				//delete mlts record
				mltss.setMltServiceId(mlts.getMltServiceId());
				session.delete(mltss);
				tx.commit();
				
		} 
		catch (RuntimeException e) {
			//TODO check for duplicate key exception and throw it
			logger.info("@ : deleteMilitaryService : exception - delete failed for mltss.mltServiceId= " + mlts.getMltServiceId());
			e.printStackTrace();
			
			if (tx != null && tx.isActive()) {
			
				try {
						tx.rollback();
					} 
					catch (HibernateException he) {
						logger.debug("@MilitaryServiceRepositoryImpl : deleteMilitaryService : exception while rolling back mlts" + he);
						he.printStackTrace();
					}
				}
				throw new RepositoryException("Exception while deleteing mlts.",e);
			}
		}

		/* (non-Javadoc)
		 * @see com.abel.repository.MilitaryServiceRepository#getMilitaryServiceInformation(com.abel.domain.PersonSearchCriteria)
		 */
		@SuppressWarnings("unchecked")
		@Override
		public MilitaryService getMilitaryService(PersonSearchCriteria criteria)
				throws RepositoryException {

		Transaction tx = null;
		Session session = null;
	    int aplId = 0;
		try {

			session = this.getSessionFactory().getCurrentSession();
			tx = session.beginTransaction();
			
			if (criteria.getApplicationId()==0) {
				
				aplId = UserSessionLocator.getUserSession().getPerson().getApplication().getApplicationId();
			
			}
			else {
				
				aplId = criteria.getApplicationId();
			
			}
			
			return getMilitaryService(aplId);
		} 
		catch (RuntimeException e) {
			
			e.printStackTrace();
			
			if (tx != null && tx.isActive()) {
			
				try {
				
					tx.rollback();
				
				}
				catch (HibernateException he) {
				
					logger.debug("@AuthRepositoryImpl : getMilitaryService : exception while getting Military Service data" + he);
					he.printStackTrace();
				
				}
			}
			throw new RepositoryException("Excpetion while getting Military Service for user Id=" + criteria.getUserId(),e);
		}

		}
		
		private MilitaryService getMilitaryService(int aplId)
		throws RepositoryException {

		Transaction tx = null;
		Session session = null;
		
		try {
			
			session = this.getSessionFactory().getCurrentSession();
			tx = session.beginTransaction();
			
			@SuppressWarnings("unchecked")
			
			List<MilitaryServices> mltList  = session.getNamedQuery("getMilitaryService").setParameter("aplId",aplId).list();
			tx.commit();
		
			if (mltList.size() == 0) {
				System.out.println("No Military Data for "+UserSessionLocator.getUserSession().getPerson().getApplication().getApplicationId());
				return null;
			}
			else {
				MilitaryServices mlss = (MilitaryServices)mltList.get(0);
				
				MilitaryService militaryService = new MilitaryService();
				militaryService.setAplId(mlss.getAplId());
				militaryService.setMltServiceId(mlss.getMltServiceId());
				militaryService.setMltBranch(mlss.getMltBranch());
				militaryService.setMltInductionDate(mlss.getMltInductionDate());
				militaryService.setMltDischargeDate(mlss.getMltDischargeDate());
				militaryService.setMltDutyDesc(mlss.getMltDutyDesc());
				militaryService.setMltSplTrainDesc(mlss.getMltSplTrainDesc());
				militaryService.setMltRank(mlss.getMltRank());
				
				return militaryService;
			}
		} 
		catch (RuntimeException e) {
			
			e.printStackTrace();
			
			if (tx != null && tx.isActive()) {
			
				try {
				
					tx.rollback();
				
				}
				catch (HibernateException he) {
				
					logger.debug("@AuthRepositoryImpl : getMilitaryService : exception while getting Military Service data" + he);
					he.printStackTrace();
				
				}
			}
			throw new RepositoryException("Excpetion while getting Military Service for Id=" + aplId,e);
		}
		}
}
